package com.ideal.frame.node.service;

import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.node.entity.NodeSyncEvent;
import com.ideal.frame.node.entity.QNodeSyncEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;

/**
 * @author: zhangdelei
 * @date: 2021/9/14-3:31 下午
 * @Description:
 **/
@Service
@Transactional
public class NodeSyncEventService {
    @PersistenceContext
    protected EntityManager entityManager;
    private JpaRepositoryImpl<NodeSyncEvent, Long> syncRepo;
    private QNodeSyncEvent qNodeSyncEvent = QNodeSyncEvent.nodeSyncEvent;

    @PostConstruct
    public void initRepo() {
        syncRepo = new JpaRepositoryImpl<>(NodeSyncEvent.class, entityManager);
    }

    /**
     * 获取最后一次同步信息
     *
     * @return
     */
    public NodeSyncEvent lastSync(int type, String prefix) {
        NodeSyncEvent event = syncRepo.selectFrom(qNodeSyncEvent)
                .where(qNodeSyncEvent.rootPrefix.eq(prefix))
                .where(qNodeSyncEvent.type.eq(type))
                .orderBy(qNodeSyncEvent.syncTime.desc()).fetchFirst();
        return event;
    }

    /**
     * 保存同步记录
     *
     * @param type
     */
    public void saveSyncEvent(int type, Date date, String prefix) {
        NodeSyncEvent event = new NodeSyncEvent();
        event.setSyncTime(date);
        event.setType(type);
        event.setRootPrefix(prefix);
        syncRepo.saveAndFlush(event);
    }
}
